/**
 * @author		Sergey Suzdalskiy
 * @e-mail:		sergey.suzdalskiy@gmail.com
 */
package ua.kiev.gcore.ui.tooltip
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.geom.Point;
	import flash.utils.Dictionary;

	public class ToolTipManager
	{
		
		
		private static var scene:Sprite;
		
		private static var tooltips:Dictionary;
		
		private static var _currentToolTipId:String;
		
		public static function enterFream():void{
			for each(var toolTip:ToolTip in tooltips){
				toolTip.enterFream();
			}
		}
		
		public static function init(target:Sprite):void{
			if(target){
				target.mouseChildren = false;
				target.mouseEnabled = false;
				
				scene = target;
			}else{
				scene = new Sprite();
			}
			tooltips = new Dictionary();
		}
		
		public static function get currentToolTipId():String{
			return _currentToolTipId;
		}
		
		public static function addToolTip(toolTip:ToolTip):String{	
			if(tooltips[toolTip.id]){
				removeToolTip(toolTip.id);
			}
			toolTip.addEventListener(ToolTipEvent.TOOL_TIP_SHOW, toolTipShowHandler);
			toolTip.addEventListener(ToolTipEvent.TOOL_TIP_HIDE, toolTipHideHandler);
			tooltips[toolTip.id] = toolTip;
			return toolTip.id;
		}
		
		public static function removeToolTip(id:String):void{
			if(tooltips[id]){
				var toolTip:ToolTip = tooltips[id];
				if(toolTip.isOnStage){
					scene.removeChild(toolTip);
					toolTip.isOnStage = false;
				}
				if(toolTip.hasEventListener(ToolTipEvent.TOOL_TIP_SHOW)){
					toolTip.removeEventListener(ToolTipEvent.TOOL_TIP_SHOW, toolTipShowHandler);
				}
				if(toolTip.hasEventListener(ToolTipEvent.TOOL_TIP_HIDE)){
					toolTip.removeEventListener(ToolTipEvent.TOOL_TIP_HIDE, toolTipHideHandler);
				}
				toolTip.destroy();
				tooltips[id] = null;
				delete tooltips[id];
			}
		}
		public static function getToolTip(id:String):ToolTip{
			var result:ToolTip;		
			if(tooltips[id]){
				result = tooltips[id];
			}
			return result;
		}
		
		private static function toolTipShowHandler(event:ToolTipEvent):void{
			var toolTip:ToolTip = event.currentTarget as ToolTip;
			_currentToolTipId = toolTip.id;
			if(!toolTip.isOnStage){
				scene.addChild(toolTip);
				toolTip.isOnStage = true;
			}
		}
		
		private static function toolTipHideHandler(event:ToolTipEvent):void{
			var toolTip:ToolTip = event.currentTarget as ToolTip;
			_currentToolTipId = null;
			if(toolTip.isOnStage){
				scene.removeChild(toolTip);
				toolTip.isOnStage = false;
			}
		}
	}
}